package bb.lanxing.util.img;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import com.umeng.analytics.pro.ar;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.util.Log;
import bb.lanxing.util.text.UriParse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class LocalImageHelper {
    static final String KEY_ALL_IMAGES = App.getContext().getString(R.string.image_chooser_all_images);
    private static final String[] STORE_IMAGES = { "_id", "_data", "datetaken"};//ar.d,
    private static final String[] THUMBNAIL_STORE_IMAGE = {"_id", "_data"};//ar.d,
    private static Context context;
    private static LocalImageHelper instance;
    private ArrayList<String> checkedPath;
    private ArrayList<Uri> checkedUri;
    private final Map<String, List<LocalFile>> folders = new HashMap();
    private final ArrayList<LocalFile> checkedItems = new ArrayList<>();
    private Handler handler = new Handler(Looper.getMainLooper());

    public interface OnLoadImageListener {
        void onLoad(Map<String, List<LocalFile>> map);

        void onUpdate(Map<String, List<LocalFile>> map);
    }

    private LocalImageHelper() {
    }

    public Map<String, List<LocalFile>> getFolderMap() {
        return this.folders;
    }

    public static LocalImageHelper getInstance() {
        if (instance == null) {
            instance = new LocalImageHelper();
        }
        return instance;
    }

    public static void init(Context context2) {
        context = context2;
    }

    public ArrayList<LocalFile> getCheckedItems() {
        return this.checkedItems;
    }


    public synchronized Map<String, List<LocalFile>> queryImage(boolean z) {
        HashMap hashMap = new HashMap();
        LinkedList linkedList = new LinkedList();
        long currentTimeMillis = System.currentTimeMillis();
        Cursor query = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES, null, null, "datetaken DESC");
        long currentTimeMillis2 = System.currentTimeMillis();
        Log.i("img-choose", "queryImage: db query cost = " + (currentTimeMillis2 - currentTimeMillis));
        if (query == null) {
            return null;
        }
        while (query.moveToNext()) {
            int i = query.getInt(query.getColumnIndexOrThrow("_id"));
            String string = query.getString(query.getColumnIndexOrThrow("_data"));
            File file = new File(string);
            if (file.exists()) {
                Uri build = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(Integer.toString(i)).build();//.appendPath(Integer.toString(i))
                String name = file.getParentFile().getName();
                LocalFile localFile = new LocalFile();
                localFile.setUri(build);
                localFile.setPath(string);
                int datataken_index = query.getColumnIndexOrThrow("datetaken");
                long time_taken = query.getLong(datataken_index);
                localFile.setTime(time_taken);
                if (z) {
                    checkedItems(localFile);
                }
                linkedList.add(localFile);
                if (hashMap.containsKey(name)) {
                    ((List) hashMap.get(name)).add(localFile);
                } else {
                    LinkedList linkedList2 = new LinkedList();
                    linkedList2.add(localFile);
                    hashMap.put(name, linkedList2);
                }
            }
        }
        if (z) {
            checkRemaining();
        }
        long currentTimeMillis3 = System.currentTimeMillis();
        Log.i("img-choose", "queryImage: build list cost = " + (currentTimeMillis3 - currentTimeMillis2));
        hashMap.put(KEY_ALL_IMAGES, linkedList);
        query.close();
        this.checkedUri = null;
        this.checkedPath = null;
        return hashMap;
    }

    public void LoadImageMap(final OnLoadImageListener onLoadImageListener) {
        Runnable runnable;
        if (this.folders.isEmpty()) {
            runnable = new Runnable() {
                @Override
                public void run() {
                    Map queryImage = LocalImageHelper.this.queryImage(true);
                    if (queryImage != null) {
                        LocalImageHelper.this.folders.putAll(queryImage);
                    }
                    if (onLoadImageListener != null) {
                        LocalImageHelper.this.handler.post(new Runnable() {
                            @Override
                            public void run() {
                                onLoadImageListener.onLoad(LocalImageHelper.this.folders);
                            }
                        });
                    }
                }
            };
        } else {
            initSelection();
            if (onLoadImageListener != null) {
                onLoadImageListener.onLoad(this.folders);
            }
            runnable = new Runnable() {
                @Override
                public void run() {
                    final Map queryImage = LocalImageHelper.this.queryImage(false);
                    if (LocalImageHelper.this.isNewMap(queryImage)) {
                        LocalImageHelper.this.initSelection();
                        if (onLoadImageListener == null) {
                            return;
                        }
                        LocalImageHelper.this.handler.post(new Runnable() {
                            @Override
                            public void run() {
                                onLoadImageListener.onUpdate(queryImage);
                            }
                        });
                    }
                }
            };
        }
        new Thread(runnable).start();
    }

    public synchronized boolean isNewMap(Map<String, List<LocalFile>> map) {
        if (map.hashCode() != this.folders.hashCode()) {
            Log.d("img-choose", "isNewMap: new folder or file found");
            this.folders.clear();
            this.folders.putAll(map);
            return true;
        }
        Log.d("img-choose", "isNewMap: no new folder or file");
        return false;
    }

    private void checkedItems(LocalFile localFile) {
        ArrayList<String> arrayList = this.checkedPath;
        if (arrayList != null && !arrayList.isEmpty()) {
            if (!this.checkedPath.contains(localFile.getPath()) || this.checkedItems.contains(localFile)) {
                return;
            }
            this.checkedItems.add(localFile);
            this.checkedPath.remove(localFile.getPath());
            return;
        }
        ArrayList<Uri> arrayList2 = this.checkedUri;
        if (arrayList2 == null || arrayList2.isEmpty() || !this.checkedUri.contains(localFile.getUri()) || this.checkedItems.contains(localFile)) {
            return;
        }
        this.checkedItems.add(localFile);
        this.checkedUri.remove(localFile.getUri());
    }

    private void checkRemaining() {
        ArrayList<String> arrayList = this.checkedPath;
        if (arrayList != null) {
            for (int size = arrayList.size() - 1; size >= 0; size--) {
                String str = this.checkedPath.get(size);
                File file = new File(str);
                if (file.exists()) {
                    LocalFile localFile = new LocalFile();
                    localFile.setPath(str);
                    localFile.setUri(Uri.fromFile(file));
                    localFile.setTime(file.lastModified());
                    this.checkedItems.add(0, localFile);
                }
            }
            return;
        }
        ArrayList<Uri> arrayList2 = this.checkedUri;
        if (arrayList2 == null) {
            return;
        }
        for (int size2 = arrayList2.size() - 1; size2 >= 0; size2--) {
            Uri uri = this.checkedUri.get(size2);
            String path = UriParse.getPath(context, uri);
            if (!TextUtils.isEmpty(path)) {
                File file2 = new File(path);
                if (file2.exists()) {
                    LocalFile localFile2 = new LocalFile();
                    localFile2.setPath(path);
                    localFile2.setUri(uri);
                    localFile2.setTime(file2.lastModified());
                    this.checkedItems.add(0, localFile2);
                }
            }
        }
    }

    public void setCheckedPath(ArrayList<String> arrayList) {
        this.checkedPath = arrayList;
        this.checkedUri = null;
        clearSelection();
    }

    public void setCheckedUri(ArrayList<Uri> arrayList) {
        this.checkedUri = arrayList;
        this.checkedPath = null;
        clearSelection();
    }

    public void initSelection() {
        if (this.checkedItems.isEmpty()) {
            for (LocalFile localFile : this.folders.get(KEY_ALL_IMAGES)) {
                checkedItems(localFile);
            }
            checkRemaining();
        }
    }

    public void clearSelection() {
        this.checkedItems.clear();
    }

    public List<LocalFile> getFolder(String str) {
        return this.folders.get(str);
    }

    public static void release() {
        LocalImageHelper localImageHelper = instance;
        if (localImageHelper != null) {
            localImageHelper.folders.clear();
            instance = null;
            context = null;
        }
    }

    public static Uri getThumbnail(Context context2, int i) {
        ContentResolver contentResolver = context2.getContentResolver();
        Uri uri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
        String[] strArr = THUMBNAIL_STORE_IMAGE;
        Cursor query = contentResolver.query(uri, strArr, "image_id = ?", new String[]{i + ""}, null);
        if (query == null) {
            return null;
        }
        if (query.getCount() > 0) {
            query.moveToFirst();
            Uri build = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI.buildUpon().appendPath(Integer.toString(query.getInt(0))).build();
            query.close();
            return build;
        }
        query.close();
        return null;
    }
}
